package com.tianji.learning.mq;

import com.tianji.api.dto.trade.OrderBasicDTO;
import com.tianji.common.constants.MqConstants;
import com.tianji.learning.service.ILearningLessonService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class LessonChangeListener {

    private final ILearningLessonService learningLessonService;


    /**
     * 监听订单支付或课程报名的消息
     * @param order 订单信息
     */
    // 定义一个RabbitMQ监听器，用于处理支付相关的消息
    // 该监听器通过绑定特定的队列、交换机和路由键来实现消息的精确消费
    // 队列名称为"learning.lesson.pay.queue"，设置为持久化队列
    // 交换机名称为"orderExchange"，类型为"topic"
    // 路由键名称为"orderPayKey"，用于精确匹配消息路由
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "learning.lesson.pay.queue", durable = "true"),
            exchange = @Exchange(name = MqConstants.Exchange.ORDER_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = MqConstants.Key.ORDER_PAY_KEY
    ))
    public void listenOrderPay(OrderBasicDTO order) {
        //1.健壮性处理
        if (order == null || order.getUserId() == null || order.getCourseIds() == null) {
            log.error("订单支付，异常消息，信息为空");
            return;
        }
        //2.添加课程
        log.debug("监听到用户{}的订单{}，需要添加课程{}到课表中", order.getUserId(),order.getOrderId(),order.getCourseIds());
        learningLessonService.addUserLessons(order.getUserId(), order.getCourseIds());
    }
}
